import {createSlice, createAsyncThunk} from '@reduxjs/toolkit';
import {deviceApi} from '@/services/api/deviceApi';
import {UserEquipmentDTO} from '@/services/api/deviceApi';
import { RESET_ALL_STATE } from '../actions/resetActions';

export const deviceTypeApiMap = {
  inv: deviceApi.getInverterInfo,
  bat: deviceApi.getBatteryInfo,
  meter: deviceApi.getMeterInfo,
};

// 获取 deviceTypeApiMap 的值的联合类型
type DeviceTypeApiMapValues =
  (typeof deviceTypeApiMap)[keyof typeof deviceTypeApiMap];

// 获取 API 函数的返回类型（Promise<ApiResponse<T>>）
type DeviceApiReturnType<T> = T extends (...args: any[]) => Promise<infer R>
  ? R
  : never;

// 获取 deviceTypeApiMap 中所有 API 函数的返回类型联合
type DeviceApiResponseUnion = DeviceApiReturnType<DeviceTypeApiMapValues>;

// 获取 API response 中 data 字段的类型联合
type DeviceApiDataUnion = DeviceApiResponseUnion extends {data: infer D}
  ? D
  : never;

// 导出 deviceTypeApiMap 的值的联合类型
export type DeviceApiDataTypes = DeviceApiDataUnion;
// 设备状态类型
interface DeviceState {
  deviceList: UserEquipmentDTO[];
  currentDevice:
    | (DeviceApiDataTypes & {deviceType: keyof typeof deviceTypeApiMap})
    | null;
  loading: boolean;
  error: string | null;
  deviceNums: Record<string, number> | null;
  defaultStationId?: number;
}

// 初始状态
const initialState: DeviceState = {
  deviceList: [],
  currentDevice: null,
  loading: true,
  error: null,
  deviceNums: null,

  /**
   * 默认电站
   * @description 默认电站是用户创建的第一个电站
   */
  defaultStationId: undefined,
};

// 异步 action：根据 SN 获取设备详情
export const fetchDeviceBySn = createAsyncThunk(
  'device/fetchDeviceBySn',
  async (params: {
    sn: string;
    stationId: number;
    deviceType: keyof typeof deviceTypeApiMap;
  }) => {
    const {sn, stationId, deviceType} = params;
    const response = await deviceTypeApiMap[deviceType]({
      deviceSn: sn,
      stationId: stationId,
    });
    return {
      ...response.data,
      deviceType: deviceType,
    };
  },
);

// 创建 slice
const deviceSlice = createSlice({
  name: 'device',
  initialState,
  reducers: {
    // 设置当前设备
    setCurrentDevice: (state, action) => {
      state.currentDevice = action.payload;
    },
    // 清空错误
    clearError: state => {
      state.error = null;
    },
    setDeviceNums: (state, action) => {
      state.deviceNums = action.payload;
    },
    setDefaultStationId: (state, action) => {
      state.defaultStationId = action.payload;
    },
    // 重置设备状态
    resetDeviceState: (state) => {
      state.deviceList = [];
      state.currentDevice = null;
      state.loading = true;
      state.error = null;
      state.deviceNums = null;
      state.defaultStationId = undefined;
    },
  },
  extraReducers: builder => {
    // 处理获取设备列表的异步状态
    builder
      // 处理获取设备详情的异步状态
      .addCase(fetchDeviceBySn.pending, state => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchDeviceBySn.fulfilled, (state, action) => {
        state.loading = false;
        state.currentDevice = action.payload;
      })
      .addCase(fetchDeviceBySn.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取设备详情失败';
      })
      // 监听全局重置action
      .addCase(RESET_ALL_STATE, (state) => {
        // 重置到初始状态
        Object.assign(state, initialState);
      });
  },
});

// 导出 actions
export const {
  setCurrentDevice,
  clearError,
  setDeviceNums,
  setDefaultStationId,
  resetDeviceState,
} = deviceSlice.actions;

// 导出 selectors
export const selectDeviceList = (state: {device: DeviceState}) =>
  state.device.deviceList;
export const selectCurrentDevice = (state: {device: DeviceState}) =>
  state.device.currentDevice;
export const selectDeviceLoading = (state: {device: DeviceState}) =>
  state.device.loading;
export const selectDeviceError = (state: {device: DeviceState}) =>
  state.device.error;
export const selectDeviceNums = (state: {device: DeviceState}) =>
  state.device.deviceNums;
export const selectDefaultStationId = (state: {device: DeviceState}) =>
  state.device.defaultStationId;
// 导出 reducer
export default deviceSlice.reducer;
